package com.gin.kotlin.gf2gamecommunity.pagingsource

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.gin.kotlin.form.CommentListForm
import com.gin.kotlin.gf2gamecommunity.app.App
import com.gin.kotlin.response.comment.CommentInfo
import com.gin.kotlin.response.topic.TopicDetail
import retrofit2.await

class CommentInfoPagingSource(private var form: CommentListForm) : PagingSource<Int, CommentInfo>() {

    companion object {
        private val TAG = CommentInfoPagingSource::class.java.simpleName
    }

    override fun getRefreshKey(state: PagingState<Int, CommentInfo>) = null

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, CommentInfo> {
        val page = params.key ?: 1
        val (topicId, sort, lastId, onlyAuthor) = form
        Log.i(TAG, "load: $page, size:${params.loadSize}, topicId:$topicId sort:$sort lastId:$lastId onlyAuthor:$onlyAuthor")
        Log.i(TAG, "load: $page, form: $form")

        try {
            // 发送请求
            val response = App.INSTANCE.api.commentApi.list(form).await()
            if (response.code != 0) {
                App.toast(response.message ?: "请求错误")
                return LoadResult.Page(listOf(), null, null)
            }
            // 响应结果
            val commentPage = response.data ?: return LoadResult.Page(listOf(), null, null)

            val res = commentPage.list.toMutableList()

            // 如果是第一页，额外请求主楼信息，将其转换为回复
            if (page == 1) {
                val topicDetail = App.INSTANCE.api.topicApi.get(form.topicId).await().data ?: return LoadResult.Page(listOf(), null, null)
                res.add(0, topicDetail.toCommentInfo())
            }

            // 修改翻页数据
            form = form.copy(lastId = commentPage.lastId)
            // 根据响应结果决定是否有下一页
            val nextKey = if (commentPage.nextPage) page + 1 else null
            // 返回结果
            return LoadResult.Page(res, null, nextKey)
        } catch (e: Exception) {
            // 处理异常
            e.printStackTrace()
            return LoadResult.Error(e)
        }
    }
}

fun TopicDetail.toCommentInfo() = CommentInfo().also {
    it.content = content
    it.createTime = createTime
    it.ipLocation = ipLocation
    it.likeNum = likeNum
    it.picList = picList
    it.userAvatar = userAvatar
    it.userId = userId
    it.userLevel = userLevel
    it.userNickName = userNickName
    it.isAdmin = isAdmin
    it.isAuthor = isAuthor
    it.isLike = isLike
}